package com.sofwin.realm;

import com.sofwin.pojo.SysUser;
import com.sofwin.service.ResourceService;
import com.sofwin.service.RoleService;
import com.sofwin.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @packageName: com.sofwin.realm
 * @user: andyliu
 * @date: 2023/1/5 16:43
 * @email 115176513@qq.com
 * @description: TODO
 */
@Component
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private ResourceService resourceService;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String loginName = principalCollection.getPrimaryPrincipal().toString();
        SysUser sysUser = userService.queryUserByLoginNameAndPwd(loginName, "");
        String roleName = roleService.queryById(sysUser.getRoleId()).getRoleName();
        // 使用3种授权方式来授权时会进入到该方法
        // 告诉shiro当前用户有哪些权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        info.setRoles(List);  // 告诉shiro当前用户拥有哪些角色
        info.addRole(roleName);
        //
//        info.setStringPermissions(); // Set<String>类型的权限，一次可以告诉shiro
        // 当前用户有哪些String权限（标记）
        // 级别1 目录
        // 界别2 菜单
        // 级别3 按钮
        // 根据角色id获取到当前角色所拥有的三级资源的permission的集合
        List<String> permissions = resourceService.queryPermissionsByRoleId(sysUser.getRoleId());
        info.addStringPermissions(permissions);
        return info;
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // subject.login 直接调用 doGetAuthenticationInfo
        UsernamePasswordToken token2 = (UsernamePasswordToken) token;
        // 客户端输入的用户名和密码
        String loginName = token2.getPrincipal().toString();
        String loginPwd = new String(token2.getPassword());
        // 密码最后需要加密码    用户输入的密码和数据库中的密码
        SysUser sysUser = userService.queryUserByLoginNameAndPwd(loginName, "");
        if(sysUser==null){
            throw new UnknownAccountException();
        }
        if(sysUser!=null && sysUser.getStatus()==1){
            throw new LockedAccountException();
        }
        return new SimpleAuthenticationInfo(loginName, sysUser.getLoginPwd(),ByteSource.Util.bytes(sysUser.getBz()),this.getName());
    }
}
